#!/usr/bin/python
from pymongo import MongoClient

def print_entry(entry):
    print("a person named " + entry['name'] + ", with age " + str(entry['age']))

def print_all(collection):
    print("")
    for entry in collection.find():
        print_entry(entry)
    print("")

client = MongoClient()
db = client['tut']
collection = db['persons']
if collection.count() > 0:
    collection.drop()

entry1 = {'name' : 'zhangsan', 'age' : 20}
entry2 = {'name' : 'lisi', 'age' : 24}
entry3 = {'name' : 'zhouwu', 'age' : 27}

collection.insert_one(entry1)
collection.insert_many([entry2, entry3])

print("traverse all the entries")
for entry in collection.find():
    print_entry(entry)
print("")

print("traverse the matched entries")
query = {'age' : {'$gt' : 22}}
for entry in collection.find(query):
    print_entry(entry)
print("")

collection.update_many({'age' : {'$gt' : 22}}, {'$inc' : {'age' : 3}})
#there is update_one as well

print_all(collection)

collection.delete_many({'age' : {'$lte' : 24}})
#there is delete_one as well

print_all(collection)


